package com.lwj.framework.web;

import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 * http请求重新封装
 *
 * @author lwj
 *
 */
public class ParamRequest extends HttpServletRequestWrapper {
	private Map<String, String> headersParams;
	private Map<String, String[]> params;

	public ParamRequest(HttpServletRequest request) {
		super(request);
		this.headersParams = new HashMap<String, String>();
		params = new HashMap<String, String[]>();
		Map<String, String[]> paramMap = request.getParameterMap();
		for (Map.Entry<String, String[]> entity : paramMap.entrySet()) {
			params.put(entity.getKey(), entity.getValue());
		}
	}

	public Map<String, String[]> getParameterMap() {
		return params;
	}

	public String getParameter(String name) {
		String[] values = params.get(name);
		if (values == null || values.length == 0) {
			return null;
		}
		return values[0];
	}

	public void addParameter(String name, Object value) {
		if (value != null) {
			if (value instanceof String[]) {
				params.put(name, (String[]) value);
			} else if (value instanceof String) {
				params.put(name, new String[] { (String) value });
			} else {
				params.put(name, new String[] { String.valueOf(value) });
			}
		}
	}

	public void addHeader(String name, String value) {
		this.headersParams.put(name, value);
	}

	public String getHeader(String name) {
		String headerValue = headersParams.get(name);
		if (headerValue != null) {
			return headerValue;
		}
		return super.getHeader(name);
	}

	public Enumeration<String> getHeaderNames() {
		Set<String> set = new HashSet<String>(headersParams.keySet());
		Enumeration<String> e = super.getHeaderNames();
		while (e.hasMoreElements()) {
			String n = e.nextElement();
			set.add(n);
		}
		return Collections.enumeration(set);
	}

}
